/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ec.socialfun.filtros;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.jboss.logging.Logger;

/**
 *
 * @author jorge
 */
public class ListenerDoubleLogin implements HttpSessionListener {

    private static final Logger log = Logger.getLogger(ListenerDoubleLogin.class.getName());

    @Override
    public void sessionCreated(HttpSessionEvent hse) {
        //log.info(".......... sessionCreated");
        //HttpSession session = hse.getSession();
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent hse) {
       // log.info(".......... sessionDestroyed");
        Map.Entry mapEntry;
        String value;
        String key;
        String sessionID ;
        HttpSession httpSession = hse.getSession();
        sessionID = httpSession.getId();
        ServletContext servletContext = httpSession.getServletContext();
        Map map = (Map) servletContext.getAttribute(FiltroDoubleLogin.SESSIONS_KEY);
        if (map.containsValue(sessionID)) {
            //log.info(".......... map.containsValue(sessionID) " + sessionID);
            Set set = map.entrySet();
            key = null;
            Iterator iterator = set.iterator();
            while (true) {
                if (iterator.hasNext() == false) {
                    break;
                }
                if (iterator.hasNext() != false) {
                    mapEntry = (Map.Entry) iterator.next();
                    value = (String) mapEntry.getValue();
                    if (value.equals(sessionID) == false) {
                        break;
                    }
                    if (value.equals(sessionID) != false) {
                        key = (String) mapEntry.getKey();
                        continue;
                    }
                }
            }
            if (key != null) {
                //log.info(".......... sessionDestroyed key " + key);
                ((Map) servletContext.getAttribute(FiltroDoubleLogin.SESSIONS_KEY)).remove(key);
            }
        }
    }
}
